package coint.btc.interceptor;

import java.io.PrintWriter;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSON;
import coint.btc.util.HttpStatus;
import coint.btc.util.WriteJson;
/**
 * session 拦截器 配置
 * @author lt
 *
 */
public class SessionInterceptor extends HandlerInterceptorAdapter{
	
	private static Logger log = LoggerFactory.getLogger(SessionInterceptor.class);  
	
	private static String [] IGNORE_URI= {"/login","/login/"}; 
	
	
	private void out(ServletResponse response, ModelMap resultMap) {
		try {
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.println(JSON.toJSONString(resultMap));
			out.flush();
			out.close();
		} catch (Exception e) {
			log.error("KickoutSessionFilter.class 输出JSON异常，可以忽略。",e);
		}
	}
	  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		  boolean flag=false;
		  String url = request.getRequestURL().toString();
		  for (String s : IGNORE_URI) {
	            if (url.contains(s)) {
	                flag = true;
	                break;
	            }
	        }
		  if(!flag) {
			  HttpSession session = request.getSession();
			  Object obj = session.getAttribute(session.getId());
			  if(obj==null) {
				  /*未登录*/
				  if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
      		          response.setHeader("sessionstatus", "timeout");//在响应头设置session状态  
      		          response.setCharacterEncoding("UTF-8");
				      response.setContentType("text/html;charset=UTF-8");
				      out(response, WriteJson.errorWebMsg(HttpStatus.NOT_LOGIN,"您已经在其他地方登陆,请重新登陆"));
	           } else {
	        	     out(response,WriteJson.errorWebMsg(HttpStatus.NOT_LOGIN, "登录失效,请重新登录"));
	           }
				  return false;
			 }
		  }
		  
		  return super.preHandle(request, response, handler);
	  }
	  
	     @Override
		public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
				throws Exception {
		}

		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
				ModelAndView modelAndView) throws Exception {
		}
	
}
